package com.wln.sms.sms.controller;

import java.io.UnsupportedEncodingException;
import java.util.*;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wln.sms.sms.config.ExceptionConfig;
import com.wln.sms.sms.entity.GoodsActivityEntity;
import com.wln.sms.sms.feign.GoodsFeignService;
import com.wln.sms.sms.service.GoodsActivityService;
import com.wln.sms.sms.util.IdWorker;
import com.wln.sms.sms.vo.ActivityGoodsVo;
import com.wln.sms.sms.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.wln.sms.sms.entity.OrderInfoEntity;
import com.wln.sms.sms.service.OrderInfoService;
import com.wln.common.utils.PageUtils;
import com.wln.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author wulinna
 * @email 2258732595@qq.com
 * @date 2022-02-22 14:30:53
 */
@Controller
@RequestMapping("sms/orderinfo")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;

    @SuppressWarnings("all")
    @Autowired
    private IdWorker idWorker;

    @Autowired
    private GoodsFeignService goodsFeignService;

    @Autowired
    private GoodsActivityService goodsActivityService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private ExceptionConfig exceptionConfig;

    private static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();

        FlowRule rule = new FlowRule();
        rule.setResource("get");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1);
        rules.add(rule);

        FlowRuleManager.loadRules(rules);
    }



    /**
     * 列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderInfoService.queryPage(params);

        return R.ok().put("page", page);
    }
    /**
     * 列表
     */
    @RequestMapping("/list1")
    @ResponseBody
    public R list1(@RequestParam Map<String, Object> params){
        PageUtils page = orderInfoService.queryPage1(params);

        return R.ok().put("page", page);
    }

    @RequestMapping("/success")
    public String success(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println(params);

        boolean signVerified = AlipaySignature.rsaCheckV2(params, com.alipay.config.AlipayConfig.alipay_public_key, com.alipay.config.AlipayConfig.charset, com.alipay.config.AlipayConfig.sign_type); //调用SDK验证签名
        String s = params.get("out_trade_no");
        OrderInfoEntity byId = orderInfoService.getById(s);
        BoundHashOperations orderinfo = redisTemplate.boundHashOps("orderinfo");
        OrderInfoEntity o = (OrderInfoEntity) orderinfo.get(byId.getOorderId());
        o.setStatus(1);
        o.setPayDate(new Date());
        orderinfo.put(s,o);

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            System.out.println("abcabcabcabcabc");
        }else {

        }
        //——请在这里编写您的程序（以上代码仅作参考）——
        return "redirect:http://seckill.com:8081/#/orderinfo";
    }


    /**
     * 列表
     */
    @RequestMapping("/topay")
    @ResponseBody
    public String topay(@RequestParam("id") long id) throws AlipayApiException {
        OrderInfoEntity byId = orderInfoService.getOne(new QueryWrapper<OrderInfoEntity>().eq("oorder_id",id));
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(com.alipay.config.AlipayConfig.gatewayUrl, com.alipay.config.AlipayConfig.app_id, com.alipay.config.AlipayConfig.merchant_private_key, "json", com.alipay.config.AlipayConfig.charset, com.alipay.config.AlipayConfig.alipay_public_key, com.alipay.config.AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(com.alipay.config.AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(com.alipay.config.AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = id+"";
        //付款金额，必填
        String total_amount = byId.getGoodsPrice()+"";
        //订单名称，必填
        String subject = byId.getGoodsName();
        //商品描述，可空
        String body = "";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{oorderId}")
    @ResponseBody
    public R info(@PathVariable("oorderId") Long oorderId){
		OrderInfoEntity orderInfo = orderInfoService.getById(oorderId);

        return R.ok().put("orderInfo", orderInfo);
    }

    /**
     * 保存
     */

    @SentinelResource(value = "get", blockHandlerClass = {ExceptionConfig.class},blockHandler = "handleException")
    @RequestMapping("/save")
    @ResponseBody
    public R save(@RequestBody ActivityGoodsVo activityGoodsVo){

        R add = orderInfoService.add(activityGoodsVo);
        return add;
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody OrderInfoEntity orderInfo){
		orderInfoService.updateById(orderInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] oorderIds){
		orderInfoService.removeByIds(Arrays.asList(oorderIds));

        return R.ok();
    }

}
